package com.futurelight.recipes.model;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.futurelight.recipes.dao.EntityResult;
import com.futurelight.recipes.repository.local.LocalRecipesRepository;
import com.futurelight.recipes.repository.remote.RemoteRecipesRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ItemViewModel extends AndroidViewModel {
    private final RemoteRecipesRepository remoteRecipesRepository;
    private final LocalRecipesRepository localRecipesRepository;
    public static List<String> types = Arrays.asList(new String[]{"main course",
            "side dish",
            "dessert",
            "appetizer",
            "salad",
            "bread",
            "breakfast",
            "soup",
            "beverage",
            "sauce",
            "marinade",
            "fingerfood",
            "snack",
            "drink"
    });

    public MutableLiveData<Common<List<Result>>> getData() {
        if (data == null) {
            data = new MutableLiveData<>();
        }
        return data;
    }

    private MutableLiveData<Common<List<Result>>> data;

    public ItemViewModel(@NonNull Application application) {
        super(application);
        remoteRecipesRepository = RemoteRecipesRepository.getInstance();
        localRecipesRepository = LocalRecipesRepository.getInstance(application);
    }


    /**
     * 获取食谱列表（网络或本地）
     * @param type
     */
    public void fetchRecipes(String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                data.postValue(new Common.Loading());
                List<Result> results = loadFromLocal(type);

                if (results != null && results.size() > 0) {
                    data.postValue(new Common.Success(results));
                } else {
                    if (hasNetWork()) {
                        loadFromRemote(type);
                    }
                }
            }
        }).start();
    }

    /**
     * 判断是否有网络
     * @return
     */
    private boolean hasNetWork() {
        return true;
    }

    /**
     * 从本地获取食谱列表
     * @param type
     * @return
     */
    private List<Result> loadFromLocal(String type) {
        List<EntityResult> entityResults = localRecipesRepository.getEntityRecipes(type);
        List<Result> results = new ArrayList<>(entityResults.size());

        for (EntityResult entityResult:entityResults){
            results.add(entityResult.result);
        }
        return results;
    }

    private void loadFromRemote(String type) {
        try {
            remoteRecipesRepository.fetchFoodRecipes(type).enqueue(new Callback<FoodRecipes>() {
                @Override
                public void onResponse(Call<FoodRecipes> call, Response<FoodRecipes> response) {
                    Common.Success<FoodRecipes> success = new Common.Success(response.body());
                    List<Result> results = response.body().results;

                    if (results == null){
                        toastError();
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            List<EntityResult> entityResults =  new ArrayList<>(results.size());
                            for (Result result : results) {
                                entityResults.add(new EntityResult(result.id,type,result.title,result));
                            }

                            localRecipesRepository.insertResult(entityResults.toArray(new EntityResult[entityResults.size()]));
                        }
                    }).start();

                    data.postValue(new Common.Success(results));
                }

                @Override
                public void onFailure(Call<FoodRecipes> call, Throwable t) {
                    toastError();
                }
            });
        } catch (Exception e) {
            toastError();
        }

    }


    void toastError(){
        Common.Error error = new Common.Error("网络加载出错");
        data.postValue(error);
    }
}
